package xin.ryven.car.android.utils

import android.content.Context
import android.os.Build
import android.os.Environment
import android.util.Log
import java.io.File
import java.io.FileWriter
import java.io.PrintWriter
import java.text.SimpleDateFormat
import java.util.*

class CrashHandler private constructor() : Thread.UncaughtExceptionHandler {
    private var mContext: Context? = null
    private var mDefaultHandler: Thread.UncaughtExceptionHandler? = null

    companion object {
        private const val TAG = "CrashHandler"
        private const val CRASH_LOG_DIR = "crash_logs"
        
        val instance: CrashHandler by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            CrashHandler()
        }
    }

    fun init(context: Context) {
        mContext = context
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler()
        Thread.setDefaultUncaughtExceptionHandler(this)
    }

    override fun uncaughtException(thread: Thread, ex: Throwable) {
        try {
            // 将崩溃信息写入文件
            dumpExceptionToFile(ex)
        } catch (e: Exception) {
            Log.e(TAG, "Error saving crash report", e)
        }

        // 调用系统默认的崩溃处理器
        mDefaultHandler?.uncaughtException(thread, ex)
    }

    private fun dumpExceptionToFile(ex: Throwable) {
        val ctx = mContext ?: return
        val dir = File(ctx.getExternalFilesDir(null), CRASH_LOG_DIR)
        if (!dir.exists()) {
            dir.mkdirs()
        }

        val timestamp = SimpleDateFormat("yyyy-MM-dd_HH-mm-ss", Locale.getDefault()).format(Date())
        val filename = "crash_$timestamp.txt"
        val file = File(dir, filename)

        try {
            PrintWriter(FileWriter(file)).use { pw ->
                // 写入设备信息
                pw.println("Device Information:")
                pw.println("Brand: ${Build.BRAND}")
                pw.println("Model: ${Build.MODEL}")
                pw.println("Android Version: ${Build.VERSION.RELEASE}")
                pw.println("SDK: ${Build.VERSION.SDK_INT}")
                pw.println("\nStack Trace:")
                ex.printStackTrace(pw)
            }
            Log.i(TAG, "Crash log saved to ${file.absolutePath}")
        } catch (e: Exception) {
            Log.e(TAG, "Error writing crash log", e)
        }
    }
} 